package cn.xspace.wnx.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.RelativeLayout;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PageUtil;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.XListView;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;
import com.xspace.android.xafcommon.view.sdlv.SlideAndDragXListView;
import com.xspace.android.xafcommon.view.sdlv.Menu;
import com.xspace.android.xafcommon.view.sdlv.MenuItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.GroupMemberListAdapter;
import cn.xspace.wnx.fragment.ChatFragment;
import cn.xspace.wnx.util.Navigator;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 点击群组信息全部成员或者转让群组时打开的界面
 * Created by liuchen on 2016/11/7.
 */
public class GroupMembersListActivity extends BaseActivity implements SlideAndDragXListView
        .OnListItemLongClickListener,
        SlideAndDragXListView.OnDragListener, SlideAndDragXListView.OnSlideListener,
        SlideAndDragXListView.OnListItemClickListener, SlideAndDragXListView.OnMenuItemClickListener,
        SlideAndDragXListView.OnItemDeleteListener, SlideAndDragXListView.OnListScrollListener {
    public static final String TAG = "GroupMembersListActivity";
    public static final String FINISH = "finishThis";
    private TitleBar mTitlebar;
    private SlideAndDragXListView<OrgDeptUserBean> memberListview;
    private RelativeLayout searchLayout;
    private ArrayList<OrgDeptUserBean> dataList = new ArrayList<>();
    private String operate = "";
    private String group_id = "";
    private String group_owner_id = "";
    private GroupMemberListAdapter mAdapter;
    private String user_id = "";
    private int pageIndex = 1;
    private int groupMember = 0;
    private int groupType = Type.GroupType.TEMP_GROUP;
    private int isQuit = 0;
    private Menu mMenu;
    private OrgDeptUserBean deleteBean;


    @Override
    protected void getIntentData() {
        super.getIntentData();
        Bundle mBundle = getIntent().getBundleExtra(BldNavigation.KEY_BUNDLER);
        if (mBundle != null) {
//            dataList = (ArrayList<OrgDeptUserBean>) mBundle.getSerializable(SelectMemberActivity.SELECTED_MEMBERS);
            operate = mBundle.getString(EventBusConstant.ACTION_KEY);
            group_id = mBundle.getString(ChatInfoActivity.GROUP_ID);
            group_owner_id = mBundle.getString(ChatInfoActivity.GROUP_OWNER);
            groupMember = mBundle.getInt(ChatInfoActivity.GROUP_MEMBER_NUMBER);
            groupType = mBundle.getInt(ChatInfoActivity.GROUP_TYPE, groupType);
            isQuit = mBundle.getInt(ChatInfoActivity.IS_QUIT, 0);
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_group_member_list);
        EventBus.getDefault().register(mContext);
    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        mTitlebar = (TitleBar) findViewById(R.id.title_bar);
        memberListview = (SlideAndDragXListView) findViewById(R.id.list_members);
        searchLayout = (RelativeLayout) findViewById(R.id.relative_search);
    }

    @Override
    protected void initData() {
        super.initData();
        user_id = MyInfoUtil.getMyUserid(mContext);
        initMenu();
        memberListview.setMenu(mMenu);
        mAdapter = new GroupMemberListAdapter(mContext, dataList);
        memberListview.setPullRefreshEnable(false);
        memberListview.setPullLoadEnable(true);
        memberListview.setAdapter(mAdapter);
        memberListview.setOnDragListener(this, dataList);
        requestNetWork();
    }

    /**
     * 初始化侧滑删除菜单
     */
    private void initMenu() {
        mMenu = new Menu(true, true);
        if (!ChatInfoActivity.GROUP_OWNER_TURN.equals(operate)) { //不是转让群组的时候,添加侧滑菜单
            if (user_id.equals(group_owner_id) &&
                    (groupType == Type.GroupType.TEMP_GROUP || groupType == Type.GroupType.NORMAL)) {
                mMenu.addItem(new MenuItem.Builder().setWidth((int) getResources().getDimension(R.dimen.space_49) + 40)
                        .setBackground(ResourceUtils.getDrawable(R.drawable.selector_btn_delete))
                        .setText(getString(R.string.delete))
                        .setDirection(MenuItem.DIRECTION_RIGHT)
                        .setTextColor(Color.WHITE)
                        .setTextSize(14)
                        .build());
            }

        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        memberListview.setOnListItemLongClickListener(this);
        memberListview.setOnListItemClickListener(this);
        memberListview.setOnSlideListener(this);
        memberListview.setOnMenuItemClickListener(this);
        memberListview.setOnItemDeleteListener(this);
        memberListview.setOnListScrollListener(this);
        memberListview.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                LogUtil.d("onLoadMore");
                pageIndex++;
                memberListview.stopLoadMore();
                requestNetWork();
            }
        });
        searchLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle mbundle = new Bundle();
//                mbundle.putSerializable(SelectMemberActivity.SELECTED_MEMBERS, dataList); //TODO 使用访问网络查找人员,不用单独传递数据
                mbundle.putString(BldNavigation.SEARCH_TYPE, BldNavigation.SEARCH_GROUP_MEMBER);
                mbundle.putString(EventBusConstant.ACTION_KEY, operate);
                mbundle.putString(ChatInfoActivity.GROUP_ID,group_id);
                mbundle.putInt(ChatInfoActivity.GROUP_TYPE,groupType);
                Navigator.startHeaderActivity(mContext, R.id.relative_search, mbundle);
            }
        });
        mTitlebar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitlebar.setRightLayoutImageVisibility(View.GONE);
        mTitlebar.setTitle(String.format(getResources().getString(R.string.group_chat_all_user), groupMember + ""));
        if (groupType == Type.GroupType.ORGANIZATION || groupType == Type.GroupType.PROFESSIONAL || isQuit == 1) {
            //专业群组和机构群组或者被踢出,不能添加人员
            mTitlebar.setRightLayoutVisibility(View.GONE);
        } else {
            mTitlebar.showRightText();
            mTitlebar.setRightLayoutTextView(getResources().getString(R.string.member_add));
            mTitlebar.setRightLayoutClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle addBundler = new Bundle();
                    addBundler.putString(ChatInfoActivity.KEY_MEMBER_OPERATE, ChatInfoActivity.MEMBER_ADD);
                    addBundler.putString(ChatInfoActivity.GROUP_ID, group_id);
                    addBundler.putString(ChatInfoActivity.GROUP_OWNER, group_owner_id);
                    addBundler.putInt(ChatInfoActivity.GROUP_TYPE,groupType); //传递群组类型,增删时需要使用
                    Navigator.startNewChatActivity(mContext, addBundler);
                }
            });
        }
    }

    /**
     * 访问网络获取数据
     */
    private void requestNetWork() {
        showWaitDialog();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(RequestConstant.KEY_USER_ID, user_id);
        dataMap.put(RequestConstant.KEY_GROUP_ID, group_id);
        mPageCommonbean.page = pageIndex;
        dataMap.put(RequestConstant.KEY_PG, mPageCommonbean);
        String url = Constants.QUERY_GROUP_MEMBERS;
        if (groupType == Type.GroupType.PROFESSIONAL) {
            url = Constants.QUERY_PRO_GROUP_MEMBERS;
        }
        registerSubscription(OkHttpManager.getInstance().commonRequest(url, dataMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<OrgDeptUserBean>>() {
                    @Override
                    public List<OrgDeptUserBean> call(BaseReturnBean baseReturnBean) {
                        List<OrgDeptUserBean> dataList = new ArrayList<OrgDeptUserBean>();
                        try {
                            JSONArray jsonArray = new JSONArray(baseReturnBean.data);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject json = jsonArray.getJSONObject(i);
                                String userId = json.optString("user_id");
                                String user_name = json.optString("user_name");
                                String user_logo = json.optString("user_logo");
                                String user_sex = json.optString("user_sex");
                                OrgDeptUserBean bean = new OrgDeptUserBean();
                                bean.user_id = userId;
                                bean.user_name = user_name;
                                bean.user_logo = user_logo;
                                bean.user_sex = user_sex;
                                if (userId.equals(group_owner_id)) {
                                    bean.isCanSlide = false;
                                }
                                dataList.add(bean);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return null;
                        }
                        return dataList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OrgDeptUserBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(List<OrgDeptUserBean> orgDeptUserBeen) {
                        hideWaitDialog();
                        if (orgDeptUserBeen == null) {
                            T.showShort(mContext, HttpException.JSON_ERROR);
                            return;
                        }
                        if (orgDeptUserBeen.size() < PageUtil.PAGE_SIZE) {
                            memberListview.setPullLoadEnable(false);
                        }

                        dataList.addAll(orgDeptUserBeen);
                        mAdapter.notifyDataSetChanged();

                    }
                }));

    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        super.onEventMainThread(inParam);
        if (TAG.equals(inParam.get(EventBusConstant.TYPE))) {
            if (FINISH.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                finish();
            }
        }
    }

    @Override
    public void onDragViewStart(int position) {

    }

    @Override
    public void onDragViewMoving(int position) {

    }

    @Override
    public void onDragViewDown(int position) {

    }

    @Override
    public void onItemDelete(View view, int position) {

    }

    @Override
    public void onListItemClick(View v, int position) {
        LogUtil.d("position " + position);
        final OrgDeptUserBean bean = dataList.get(position - 1);
        if (ChatInfoActivity.GROUP_OWNER_TURN.equals(operate)) {
            DialogHelp.getConfirmDialog(mContext,
                    String.format(getResources().getString(R.string.group_owner_turn_confirm), bean.user_name),
                    "",
                    getResources().getString(R.string.think_again_and_again),
                    getResources().getString(R.string.button_ok),
                    null, new ButtonClickListener() {
                        @Override
                        public void buttonClick(View view) {
                            LogUtil.d(bean.toString());
                            Map<String, Object> dataMap = new HashMap<String, Object>();
                            dataMap.put(EventBusConstant.TYPE, ChatInfoActivity.TAG);
                            dataMap.put(EventBusConstant.ACTION_KEY, ChatInfoActivity.GROUP_OWNER_TURN);
                            dataMap.put(EventBusConstant.ACTION_VALUE, bean);
                            EventBus.getDefault().post(dataMap);
                            finish();
                        }
                    })
                    .setContentVisible(View.GONE)
                    .show();

        } else {
            Navigator.startPersonCardActivity(mContext, bean.user_id);
        }
    }

    @Override
    public void onListItemLongClick(View view, int position) {

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

//    Subscriber<BaseReturnBean> deleteMemberSub =

    @Override
    public int onMenuItemClick(View v, int itemPosition, int buttonPosition, int direction) {
        switch (direction) {
            case MenuItem.DIRECTION_LEFT:
                switch (buttonPosition) {
                    case 0:
                        return Menu.ITEM_NOTHING;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
                break;
            case MenuItem.DIRECTION_RIGHT:
                switch (buttonPosition) {
                    case 0:
                        LogUtil.d("itemPosition  " + itemPosition);
                        int position = itemPosition;
                        LogUtil.d("position  " + position);
                        deleteBean = dataList.get(position);
                        showConfirmDialog(deleteBean);
                        return Menu.ITEM_SCROLL_BACK;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
        }
        return Menu.ITEM_NOTHING;
    }

    /**
     * 弹出删除确认对话框
     *
     * @param deleteBean
     */
    private void showConfirmDialog(final OrgDeptUserBean deleteBean) {
        DialogHelp.getConfirmDialog(mContext,
                String.format(getResources().getString(R.string.group_member_delete_confirm), deleteBean.user_name),
                "",
                getResources().getString(R.string.think_again_and_again),
                getResources().getString(R.string.delete),
                null,
                new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        deleteMember(deleteBean);
                    }
                })
                .setContentVisible(View.GONE).show();
    }

    private void deleteMember(final OrgDeptUserBean deleteBean) {
        showWaitDialog();
        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put(RequestConstant.KEY_USER_ID, user_id);
        deleteMap.put(RequestConstant.KEY_GROUP_ID, group_id);
        List<OrgDeptUserBean> deleteList = new ArrayList<>();
        deleteList.add(deleteBean);
        deleteMap.put(RequestConstant.KEY_USER_LIST, deleteList);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.EXIT_GROUP, deleteMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        groupMember -= 1;
                        mTitlebar.setTitle(String.format(getResources().getString(R.string.group_chat_all_user),
                                groupMember + ""));
                        //更新相关UI
                        dataList.remove(deleteBean);
                        mAdapter.notifyDataSetChanged();
                        Map<String, Object> dataMap = new HashMap<>();
                        dataMap.put(EventBusConstant.TYPE, ChatInfoActivity.TAG);
                        dataMap.put(EventBusConstant.ACTION_KEY, ChatInfoActivity.GROUP_MEMBER_DELETE);
                        EventBus.getDefault().post(dataMap);
                        Map<String, Object> chatMap = new HashMap<>();
                        chatMap.put(EventBusConstant.TYPE, ChatFragment.TAG);
                        chatMap.put(EventBusConstant.ACTION_KEY, ChatInfoActivity.GROUP_MEMBER_DELETE);
                        EventBus.getDefault().post(chatMap);
                    }
                }));

    }

    @Override
    public void onSlideOpen(View view, View parentView, int position, int direction) {

    }

    @Override
    public void onSlideClose(View view, View parentView, int position, int direction) {

    }
}
